from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from register.models import Player
from .models import loginRecord
from recordsLibrary.views import addRecord
from visualization.models import playerLog
import json

# Create your views here.
def login(request):
    record=loginRecord(
        where=request.get_host(),
        how=request.path_info,
        method=request.method
        )
    method=request.method
    if method=='POST':
        loginEmail=request.POST.get('email')
        record.who=loginEmail
        result=Player.objects.filter(email=loginEmail)
        if len(result)==0:
            record.success=False
            addRecord(record)
            return JsonResponse({'error':'邮箱未注册'})
        if result[0].pwd==request.POST.get('pwd'):
            record.success=True
            addRecord(record)
            re=JsonResponse({'status':1})
            re.set_cookie('email',loginEmail)
            re.set_cookie('nickname',json.dumps(result[0].nickname))
            log=playerLog.objects.filter(email=loginEmail)
            log.update(logins=log[0].logins+1)
            return re
        else:
            record.success=False
            addRecord(record)
            return JsonResponse({'error':'密码错误'})
    if method=='GET':
        record.success=True
        addRecord(record)
        return render(request,'login.html',{'title':'login'})